﻿#region

using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc;
using BTL.OnlineTestingSocial.Application.Web.Infrastructure.ViewModels.ViewModelMapper;
using BTL.Technology.Framework;
using BTL.Technology.Framework.Extensions;

#endregion

namespace BTL.OnlineTestingSocial.Application.Web.Infrastructure
{
    public class ExHttpApplication : HttpApplication
    {
        protected IContainer Container;

        public List<IModule> AutofacModules { get; set; }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        protected void Application_Start()
        {
            RegisterGlobalFilters(GlobalFilters.Filters);

            RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            RegisterObjectFactory();

            ControllerBuilder.Current.SetControllerFactory(GetControllerFactory());

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(GetViewEngine());

            BindModels();

            AutoMapperConfiguration.Configure();
        }

        protected virtual void RegisterAllAreas()
        {
        }

        protected virtual void RegisterRoutes(RouteCollection routeCollection)
        {
        }

        protected virtual void RegisterObjectFactory()
        {
            Guard.Assert(AutofacModules == null && !AutofacModules.Any(),
                         "Dont have any autofac module for register instances");

            var builder = new ContainerBuilder();

            builder.RegisterModules(AutofacModules);
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterFilterProvider();

            Container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
        }

        protected virtual IControllerFactory GetControllerFactory()
        {
            return new DefaultControllerFactory();
        }

        protected virtual IViewEngine GetViewEngine()
        {
            return new RazorViewEngine();
        }

        protected virtual void BindModels()
        {
        }
    }
}